package com.aggregate.pay.quanzi.support;

import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aggregate.pay.quanzi.support.utils.JSON;
import com.aggregate.pay.quanzi.support.utils.RSA;
import com.aggregate.pay.quanzi.support.utils.SHA1;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 圈子支付接口专属工具类
 * @author Moyq5
 * @date 2018年11月24日
 */
public class Tool {
	
	private static Logger log = LoggerFactory.getLogger(Tool.class);
	

	public static Map<String, String> sign(Object data, String key) throws Exception {
		return sign(JSON.toString(data), key);
	}
	
	public static boolean verify(String json, String publicKey) {
		TreeMap<String, String> map = JSON.toObject(json, new TypeReference<TreeMap<String, String>>() {});
		return verify(map, publicKey);
	}
	
	public static boolean verify(Map<String, String> map, String publicKey) {
		String sign = map.get("signature");
		log.debug("圈子->响应签名值：{}", sign);
		map.remove("signature");
		String data = toQueryString(map);
		try {
			RSA.verify(data.getBytes("UTF-8"), publicKey, sign);
		} catch (Exception e) {
			log.error("圈子->响应签名验证失败", e);
			return false;
		}
		return true;
	}
	
	private static Map<String, String> sign(String json, String key) throws Exception {
		Map<String, String> map = JSON.toObject(json, new TypeReference<TreeMap<String, String>>() {});
		map.remove("signature");
		String sign = sign(map, key);
		map.put("signature", sign);
		return map;
	}
	
	private static String sign(Map<String, String> map, String key) {
		String sign = toQueryString(map);
		log.debug("圈子->签名内容：{}", sign);
		sign = SHA1.encrypt(sign);
		log.debug("圈子->签名内容SHA1：{}", sign);
		try {
			sign = RSA.sign(sign.getBytes("UTF-8"), key);
		} catch (Exception e) {
			log.error("圈子->签名异常", e);
		}
		log.debug("圈子->签名内容RSA：{}", sign);
		log.debug("圈子->签名值：{}", sign);
		return sign;
	}
	
	private static String toQueryString(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry: map.entrySet()) {
			if (null != entry.getValue() && !entry.getValue().isEmpty()) {
				sb.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
		}
		sb.deleteCharAt(sb.length()-1);// 去掉最后的“&”
		return sb.toString();
	}

}